package com.hex.ds.em.hcdp.gauss.analyze.script.normal;

import static com.hex.ds.em.hcdp.gauss.pack.service.impl.ScriptPackTaskServiceImpl.wordResult;

import cn.hutool.core.util.StrUtil;
import com.hex.ds.em.hcdp.basic.common.IResultForReport;
import com.hex.ds.em.hcdp.gauss.analyze.script.normal.entity.CheckCreateTableGrammarEntity;
import com.hex.ds.em.hcdp.gauss.common.entity.ScriptPackScanResultEntity;
import com.hex.ds.em.hcdp.gauss.common.enums.AntlrEnum;
import com.hex.hlrt.gauss.g4.basic.gen.GaussParser;
import com.hex.hlrt.gauss.g4.basic.gen.GaussParserBaseListener;
import lombok.RequiredArgsConstructor;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

/**
 * @Package com.hex.ds.em.hcdp.gauss.analyze.script.performance
 * @ClassName CheckUnionAllListener
 * @Description 检查建表语句，是否是 CREATE TABLE IF EXISTS XXX CREATE TABLE XXX
 * @Author gj.xu
 * @Date 2024/9/14 15:52
 * @Version v2.0
 **/
@Slf4j
@Accessors(chain = true)
@Scope(value = "prototype")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Service("Gauss-CheckCreateTableGrammar")
public class CheckCreateTableGrammarListener extends GaussParserBaseListener implements IResultForReport {

  @Override
  public void exitCreate_table(GaussParser.Create_tableContext ctx) {
    if (isCreateTableIfExists(ctx) || isCreateTable(ctx)) {
      // 更新扫描后word指标结果
      setResultForWordReport();

      CheckCreateTableGrammarEntity ruleEntity = new CheckCreateTableGrammarEntity();
      ctx.addHeadAnyChild(ruleEntity);
      log.info("rule-[CheckCreateTableGrammar]:");
    }
  }

  /**
   * @Method isCreateTableIfExists
   * @Param ctx
   * @Return java.lang.Boolean
   * @Description 判断是否为 CREATE TABLE IF EXISTS XXX
   * @Author gj.xu
   * @Date 2024/9/20 16:17
   * @Version V2.0
   */
  private Boolean isCreateTableIfExists(GaussParser.Create_tableContext ctx) {
    return ctx.IF() != null && ctx.NOT() == null && ctx.EXISTS() != null;
  }

  /**
   * @Method isCreateTable
   * @Param ctx
   * @Return java.lang.Boolean
   * @Description 判断是否为 CREATE TABLE XXX
   * @Author gj.xu
   * @Date 2024/9/20 16:17
   * @Version V2.0
   */
  private Boolean isCreateTable(GaussParser.Create_tableContext ctx) {
    return ctx.IF() == null && ctx.NOT() == null && ctx.EXISTS() == null;
  }

  @Override
  public void setResultForWordReport() {
    ScriptPackScanResultEntity result = wordResult.get(AntlrEnum.CHECK_CREATE_TABLE_GRAMMAR.getValue());
    if (result == null) {
      return;
    }
    result.setScanTable("").setScanState("fail");
    wordResult.put(AntlrEnum.CHECK_CREATE_TABLE_GRAMMAR.getValue(), result);
  }
}
